<template>
  <div class="app-Inquiry" style="margin: 0 !important;">
    <div class="top-container">
      <el-form
        :inline="true"
        :model="formInline"
        ref="formInline"
        class="demo-form-inline"
        style="display: block !important;"
      >
        <el-form-item label="后台单号" style="margin-bottom: 15px!important;">
          <el-input
            v-model.trim="formInline.xmbzNo"
            clearable
            size="medium"
            placeholder="后台单号"
            style="width: 163px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="城市" style="margin-bottom: 15px!important;">
          <el-select
            ref="deptRef"
            v-model="formInline.cityId"
            placeholder="城市"
            size="medium"
            style="width: 100px;"
            @change="handleCity"
            @keydown.native="selectBlur($event)"
          >
            <el-option
              v-for="(house,citykey) in cityselect"
              :key="citykey"
              :label="house.deptName"
              :value="house.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流状态" style="margin-bottom: 15px!important;">
          <el-select
            ref="statusRef"
            v-model="formInline.state"
            clearable
            size="medium"
            placeholder="物流状态"
            style="width: 130px"
            @keydown.native="selectBlur($event)"
          >
            <el-option
              v-for="item in statusList"
              :key="item.status"
              :label="item.statusName"
              :value="item.status"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="分仓" style="margin-bottom: 15px!important;">
          <el-select
            ref="barnchWarehouseRef"
            v-model="formInline.warehouseId"
            @keydown.native="selectBlur($event)"
            clearable
            filterable
            size="medium"
            placeholder="分仓"
            style="width: 155px"
          >
            <el-option
              v-for="(item,index) in barnchWarehouselist"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item sytle="dispaly:flex">
          <el-date-picker
            v-model="formInline.timeValue"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :picker-options="pickerOptions"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            size="medium"
            align="right"
          ></el-date-picker>
        </el-form-item>
        <el-form-item style="margin-bottom: 15px!important;">
          <el-button
            type="primary"
            @click="onSubmit"
            size="medium"
            plain
            icon="el-icon-search"
            style="margin-left: 30px;"
          >查询
          </el-button>
          <el-button
            @click="onExport"
            size="medium"
            plain
            icon="el-icon-download"
            class="ml-5 mt-0"
          >导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-table
        ref="table"
        class="table-width"
        :data="querylist"
        header-row-class-name="table-top"
        style="width: 100%"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="顺丰物流id">
                <span>{{ props.row.id}}</span>
              </el-form-item>
              <el-form-item label="距离">
                <span>{{ props.row.deliveryDistance }}</span>
              </el-form-item>
              <el-form-item label="接单时间">
                <span>{{ props.row.receivingTime }}</span>
              </el-form-item>
              <el-form-item label="到店时间">
                <span>{{ props.row.arriveTime }}</span>
              </el-form-item>
              <el-form-item label="取件时间">
                <span>{{ props.row.pickupTime }}</span>
              </el-form-item>
              <el-form-item label="签收时间">
                <span>{{ props.row.signTime }}</span>
              </el-form-item>
              <el-form-item label="取消时间">
                <span>{{ props.row.cancelTime }}</span>
              </el-form-item>
              <el-form-item label="创始人" >
                <span>{{ props.row.createName }}</span>
              </el-form-item>
              <el-form-item label="取消人" >
                <span>{{ props.row.cancelUser }}</span>
              </el-form-item>
              <el-form-item label="当前节点" >
                <span>{{ props.row.traceNode }}</span>
              </el-form-item>
              <el-form-item label="当前节点备注" label-width="100px">
                <span>{{ props.row.traceMark }}</span>
              </el-form-item>
              <el-form-item label="当前节点时间" label-width="100px">
                <span>{{ props.row.traceTime }}</span>
              </el-form-item>
              <el-form-item style="width: 100%" label="收货地址">
                <span>{{ props.row.receiverAddress }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" align="center" min-width="60">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ getOrderStatus(scope.row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="商品类型" align="center"></el-table-column>
        <el-table-column prop="xmbzNo" label="单号" align="center"></el-table-column>
        <el-table-column label="城市名称" prop="cityName" align="center"></el-table-column>
        
        <el-table-column prop="wareName" label="仓库名称" align="center"></el-table-column>
        <el-table-column prop="waybillOrder" label="运单号" align="center"></el-table-column>
        <el-table-column prop="driverName" label="骑手" align="center"></el-table-column>
        <el-table-column prop="driverMobile" label="骑手电话"></el-table-column>
        <el-table-column prop="state" label="顺丰物流状态" align="center">
          <template slot-scope='scope'>
            <span>{{changeJDstatus(scope.row.state)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="responsibleDepartmentErrorText" label="部门失误类型" align="center" min-width="200">
          <template slot-scope='scope'>
            <span class="el-button--text cs-p" @click="viewResponsibleDetail(scope.row)">
              {{scope.row.responsibleDepartmentErrorText}}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryStartTime" label="配送开始时间" align="center" width="150"></el-table-column>
        <el-table-column prop="deliveryEndTime" label="配送结束时间" align="center" width="150"></el-table-column>
        <el-table-column prop="createTime" label="发布时间" align="center" width="150"></el-table-column>
        <el-table-column prop="deliveryDistance" label="配送里程" align="center"></el-table-column>
        <el-table-column prop="deliveryMoney" label="配送金额" align="center"></el-table-column>
        <el-table-column prop="cancelMoney" label="订单补偿金" align="center"></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button v-show="!(scope.row.state==10||scope.row.state==-1)" type="danger" size="mini" @click="cancelOrder(scope.row)">取消订单</el-button>
            <el-button type="success" size="mini" @click="handshowDayItem(scope.row)">查看日志</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="formInline.current"
        :limit.sync="formInline.size"
        @pagination="getList"
      />
    </div>

      <!-- 日志进度 -->
      <el-dialog
            title="日志进度"
            :visible.sync="islogProgress"
            width="50%" >
        <el-radio-group v-model="reverse">
          <el-radio :label="true">倒序</el-radio>
          <el-radio :label="false">正序</el-radio>
        </el-radio-group>
            <!-- 时间线 -->
            <el-timeline :reverse="reverse" class="mt-10">
                <el-timeline-item
                v-for="(item, index) in this.logProgress"
                :key="index"
                :timestamp="item.createTime">
                <p>{{item.operator}}</p>
                <h3>【{{item.traceNode}}】{{item.traceMark}}</h3>
                </el-timeline-item>
            </el-timeline>
      </el-dialog>

      <!-- 取消订单 -->
       <el-dialog
            title="取消订单"
            :visible.sync="iscancellationOrder"
            width="50%" >
        <div style="display: flex; align-items: center; margin-bottom: 20px;">
            <span style="margin-right: 20px">请选择取消订单选项:</span>
            <el-select v-model="iscancellationSelect" slot="prepend" placeholder="请选择取消订单选项" class="w-300">
              <el-option-group
                v-for="group in cancelOptions"
                :key="group.label"
                :label="group.label">
                <el-option
                  v-for="item in group.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-option-group>
            </el-select>
        </div>
        <div style="display: flex; align-items: center;">
          <span style="width:80px">取消备注:</span>
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容(可以不输入备注)"
            v-model="textarea">
        </el-input>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="iscancellationOrder = false" style="margin-right: 50px">取 消</el-button>
          <el-button type="primary" @click="goCancelorder">确 定</el-button>
        </span>
      </el-dialog>

      <complaintDetailDialog ref="complaintDetailDialog"></complaintDetailDialog>
  </div>
</template>

<script>
  import {
    statusList,
    getWarehouseListByCityId
  } from "@/api/pending";
  import {
    citySelect, // 城市
  } from "@/api/createOrder";
  import {
    logisticsList,   // 列表 搜索
    showDaytitle,  // 日志授权
    cancellationOrder,  //取消发布订单
    exportList,
  } from "@/api/sf-order";
  import {
    uuStatusList,
  } from "@/api/uu-apis";
  import Pagination from "@/components/Pagination";
  import complaintDetailDialog from '@/components/order/complaintDetailDialog'
  import {download, downloadByUrl} from '@/util/file'

  const cancelOptions = [{
    label: '骑手到店前取消',
    options: [{
      label: '计划有变，暂时不需要寄件了',
      value: '300'
    }, {
      label: '填错订单信息，取消后重新提交',
      value: '302'
    }, {
      label: '重复下单，取消此单',
      value: '306'
    }, {
      label: '骑士上门时间太长',
      value: '309'
    }, {
      label: '无人接单，换用其他平台寄件',
      value: '312'
    }, {
      label: '其他，请注明原因',
      value: '313'
    }]
  }, {
    label: '骑手到店后取消',
    options: [{
      label: '暂时无法提供配送物品',
      value: '304'
    }]
  }]
  export default {
    components: {
      Pagination,
      complaintDetailDialog
    },
    data() {
      return {
        cancelOptions,
        ischangedata: {}, //选中的数据
        textarea: '', //备注内容
        iscancellationSelect: '', //取消订单原因
        iscancellationOrder: false,  //取消订单 
        islogProgress: false, //显示日志
        logProgress: [], // 日志列表
        reverse: false, // 日志顺序
        barnchWarehouselist: [],
        total: 0,
        deptId: "",
        formInline: {
          cityId: 0, // 城市id
          xmbzNo: "", // 后台单号
          status: "",
          timeValue: [// 查询时间值
            this.dayjs(new Date()).format("YYYY-MM-DD 00:00:00"),
            this.dayjs(new Date()).format("YYYY-MM-DD 23:59:59")],
          warehouseId: '',
          current: 1,
          size: 10
        },
        querylist: [],
        Loading: true,
        statusList: [], // 状态
        orderStatusList: [], // 状态
        pickerOptions: {
          onPick: obj => {
            this.pickerMinDate = new Date(obj.minDate).getTime();
          },
          disabledDate: time => {
            if (this.pickerMinDate) {
              const day1 = 31 * 24 * 3600 * 1000;
              let maxTime = this.pickerMinDate + day1;
              let minTime = this.pickerMinDate - day1;
              return time.getTime() > maxTime || time.getTime() < minTime;
            }
          }
        },
        cityselect: "", // 城市获取列表

      };
    },
    created() {
      window.addEventListener("keydown", this.keyupEnter);
    },
    watch: {},
    mounted() {
      citySelect(this.cityLi).then(res => {
        res.data.data.unshift({
          id: 0,
          deptName: "全国"
        });
        this.formInline.cityId = res.data.data[0].id;
        this.cityselect = res.data.data;
      });
      this.getWarehouseList();
      // 状态列表接口
      this.statusList = uuStatusList();
      //订单状态
      // 状态列表接口
      statusList().then(res => {
        this.orderStatusList = res.data.data || [];
      });
      this.getList();
    },
    methods: {
      goCancelorder(){
        if(!this.iscancellationSelect){
          this.$message({
            message: '请选择取消订单先选项',
            type: 'warning'
          });
          return
        }
        let data = {
          xmbzNo:this.ischangedata.xmbzNo,
          cancelCode: this.iscancellationSelect,
          userName: this.$store.state.user.userInfo.userName,
          cancelReason: this.textarea
        }
        cancellationOrder(data).then(res=>{
          if(res.data.code == 200 ){
            this.$notify({
              title: '成功',
              message: '取消订单成功',
              type: 'success'
            });
            this. iscancellationOrder = false;
            this. textarea = ''
            this. iscancellationSelect = '',
            this.getList()
          }else{
            this.$notify.error({
              title: '错误',
              message: '取消订单失败'
            });
          }
        })
      },
      handshowDayItem(item){
        showDaytitle({logisticsId:item.id}).then(res=>{
          this.islogProgress = true
          this.logProgress = res.data.data.records 
        })
      },
      changeJDstatus(id){
        const statusLabelMap = {
          1: '下单成功',
          3: '抢单成功',
          4: '已到达',
          5: '已取件',
          6: '妥投',
          '-1': '订单取消',
        }
        return statusLabelMap[id] || '-'
      },
      getUuStatus(id){
        for (let i = 0; i < this.statusList.length; i++) {
          if(this.statusList[i].status == id){
            return this.statusList[i].statusName;
          }
        }
      },
      getOrderStatus(id){
        for (let i = 0; i < this.orderStatusList.length; i++) {
          if(this.orderStatusList[i].status == id){
            return this.orderStatusList[i].statusName;
          }
        }
      },
      // 获取城市
      handleCity() {
        this.formInline.warehouseId = ''
        this.getWarehouseList();
      },
      getWarehouseList() {
        getWarehouseListByCityId({cityId: this.formInline.cityId}).then(res => {
          this.barnchWarehouselist = res.data.data;
        });
      },
      onSubmit() {
        this.formInline.current = 1;
        this.getList();
      },
      getParams() {
        const params = {
          xmbzNo: this.formInline.xmbzNo, // 后台单号
          state: this.formInline.state,
          warehouseId: this.formInline.warehouseId,
          current: this.formInline.current,
          size: this.formInline.size,
          cityId: this.formInline.cityId == 0 ? undefined : this.formInline.cityId,
          deliveryStartTime: this.formInline.xmbzNo ? '' : this.formInline.timeValue[0],
          deliveryEndTime: this.formInline.xmbzNo ? '' : this.formInline.timeValue[1],
        }
        return params
      },
      onExport() {
        const params = this.getParams()
        if (this.$refs.table && this.$refs.table.selection && this.$refs.table.selection.length) {
          params.ids = this.$refs.table.selection.map(item => item.id).join(',')
        }
        downloadByUrl('/api/xmbz-sftc/sftclogisticsorder/export', params)
        // exportList(params).then(res => {
        //   if (res.data) {
        //     download(res.data, `顺丰订单_${this.dayjs(new Date()).format("YYYY-MM-DD 00:00")}.xls`)
        //   } else {
        //     this.$message({
        //       message: '下载失败，请重试或联系管理员',
        //       type: 'error'
        //     })
        //   }
        // })
      },
      // 查询列表
      getList() {
        if (!this.formInline.xmbzNo &&
          (!this.formInline.timeValue || this.formInline.timeValue.length < 2)) {
          this.$message.warning('请输入搜索时间，且跨度不能超过31天');
          return false;
        }
        this.Loading = true;
        const params = this.getParams()
        logisticsList(params).then(res=>{
          this.total = res.data.data.total
          this.querylist = res.data.data.rows
          setTimeout(() => {
              this.Loading = false;
            }, 0.5 * 1000);
        })
      },
      
      // 静止输入空格
      keydown(event) {
        if (event.keyCode == 32) {
          event.returnValue = false;
        }
        if (event.keyCode == 13) {
          this.$refs["channelTypeRef"].blur();
          this.$refs["channelRef"].blur();
          event.returnValue = false;
        }
      },
      // 回车事件
      keyupEnter() {
        // const that = this;
        if (window.event.keyCode == 13) {
          this.onSubmit();
        }
      },
      selectBlur(e) {
        if (e.keyCode == 13) {
          this.$refs["deptRef"].blur();
          this.$refs["statusRef"].blur();
          this.$refs["selectRef"].blur();
          this.$refs["barnchWarehouseRef"].blur();
          e.returnValue = false;
        }
      },
      temNselectBlur(e) {
        if (e.keyCode == 32) {
          e.returnValue = false;
        }
      },
      //取消订单
      cancelOrder(order){
        this.iscancellationOrder = true 
        this.ischangedata = order
        
      },
      viewResponsibleDetail(order) {
        this.$refs.complaintDetailDialog.show(order)
      }
    },
    destroyed() {
      window.removeEventListener("keydown", this.keyupEnter);
    },
    activated() {
      window.addEventListener("keydown", this.keyupEnter);
    },
    //如果页面有keep-alive缓存功能，这个函数会触发
    deactivated() {
      window.removeEventListener("keydown", this.keyupEnter);
    }
  };
</script>

<style lang="scss" scoped>
  .red {
    color: #ff0000;
  }

  .app-Inquiry {
    padding-right: 5px;

    .top-container {
      padding: 20px 10px 10px 20px;

      .el-form {
        .el-form-item {
          .line {
            margin: 0 3px;
            color: #8c919c;
          }
        }
      }

      .demo-form-inline {
        display: inline-block;
      }

      .el-form-item {
        margin-bottom: 20px !important;
      }
    }

    .table-container {
      padding-left: 20px;

      .table-top {
        font-size: 13px;

        th {
          padding: 5px 2px;

          .cell {
            padding: 0;
          }
        }
      }

      .el-table {
        .el-col-primary {
          margin: 0;
          padding: 2px 2px;
          font-size: 12px;
          font-weight: 400;
          border-radius: 4px;
          width: 78%;

          &.mainbutton {
            background: #ecf5ff;
            color: #409eff;
            border: 1px solid #b3d8ff;
          }

          &.dangerbutton {
            background: #fef0f0;
            color: #f56c6c;
            border: 1px solid #fbc4c4;
          }

          &.infobutton {
            background: #f4f4f5;
            color: #909399;
            border: 1px solid #d3d4d6;
          }

          &.warnbutton {
            background: #fdf6ec;
            color: #e6a23c;
            border: 1px solid #f5dab1;
          }
        }
      }

      .el-table__row {
        td {
          padding: 15px 2px;
          font-size: 13px;
          font-weight: 600;

          .cell {
            padding: 0;

            span {
              margin-left: 0;
            }
          }
        }
      }

      .active {
        color: #409eff;
        font-size: 13px;
        font-weight: 600;
      }

      .buttoncolor {
        color: #000;
        font-size: 13px;
        font-weight: 600;
      }

      .warning-row {
        background: oldlace;
        color: #e6a23c;
      }

    }
  }
  .el-button+{
    .el-button{
      margin-left: 0;
      margin-top: 8px;
    }
  }
  .el-date-range-picker .el-picker-panel__footer .el-button--text span {
    display: none;
  }

  .table-width {
    .el-table__fixed {
      .el-table__fixed-body-wrapper {
        .el-table__body {
          .el-table__row {
            td {
              .cell {
                span {
                  margin-left: 0 !important;
                }
              }
            }
          }
        }
      }
    }
  }

  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 33%;
  }
</style>
